package com.netrust.quarz.controller;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.netrust.quarz.dao.ServerDao;
import com.netrust.quarz.entity.Server;
import com.netrust.quarz.service.BulidAlarmHistoryService;
import com.netrust.quarz.service.BulidAlarmRealService;
import com.netrust.quarz.service.BulidStateService;
import com.netrust.quarz.utils.ProdUtils;
import com.netrust.quarz.utils.ReflectUtils;

@Controller
@RequestMapping("/m")
public class MsgController {
	
	@Autowired
	BulidAlarmHistoryService bulidAlarmHistoryService;
	@Autowired
	BulidAlarmRealService bulidAlarmRealService;
	@Autowired
	BulidStateService bulidStateService;
	@Autowired
	ServerDao serverDao;
	
	@GetMapping("sr")
	public String flushServerObjectIds(@RequestParam("op") String op,Model model) throws Exception {
		
		List<String> strs=bulidStateService.http_run_server(op);
		
		List<Server> serverList=serverDao.findByCarrier(ProdUtils.op2oe(op).getName());
		List<Server> updateServers=Lists.newArrayList();

		List<Map<String,String>> objects=Lists.newArrayList();
		for (String str : strs) {
			@SuppressWarnings("unchecked")
			Map<String,Object> map=JSONObject.parseObject(str, Map.class);
			
			 for (Map.Entry<String, Object> entry : map.entrySet()) {
				 if (entry.getKey().equals("servers")) {				
				    JSONArray ja=JSONObject.parseArray(String.valueOf(entry.getValue()));
				    JSONObject json = null;
				    HashMap<String,String> dataMap = null;  
				    for (int i=0;i<ja.size();i++) {
				    	json=ja.getJSONObject(i);
				    	
				    	dataMap = new LinkedHashMap<String,String>();  
				    	
				    	String ip_addr=json.getString("ip_addr");
				    	String object_code=json.getString("object_code");
				    	Server server=this.findIpEuqalServer(serverList, ip_addr);
				    	
				    	if(server!=null){
				    		if(StringUtils.isBlank(server.getObjectId())){
				    			server.setObjectId(object_code);
				    			updateServers.add(server);
				    		}else{
				    			if(!object_code.equals(server.getObjectId())){
				    				server.setObjectId(object_code);
					    			updateServers.add(server);
				    			}
				    		}
				    	}
				    	
				    	dataMap.put("ip_addr",ip_addr);  
				    	dataMap.put("object_code",object_code);  
				    	dataMap.put("cpuquantity",json.getString("cpuquantity"));  
				    	dataMap.put("mem_num",json.getString("mem_num"));  
				    	dataMap.put("disk_total",json.getString("disk_total")); 
				    	
				    	objects.add(dataMap);					
					}
				}
			}
		}
		
		serverDao.save(updateServers);
		
		model.addAttribute("op",op);
		model.addAttribute("collects",objects);
		
		return "original";
	}
	
	
	
	@GetMapping("st")
	public String getState(@RequestParam("op") String op,Model model) throws Exception {
		
		String str=bulidStateService.http_run(op);
		
		List<Map<String,Object>> objects=Lists.newArrayList();
		
		@SuppressWarnings("unchecked")
		Map<String,Object> map=JSONObject.parseObject(str, Map.class);
		
		HashMap<String,Object> dataMap = null;  
		for (Map.Entry<String, Object> entry : map.entrySet()) {
			JSONObject jo=JSONObject.parseObject(String.valueOf(entry.getValue()));
			
	    	dataMap = new LinkedHashMap<String,Object>();  
	    	dataMap.put("objectId",entry.getKey());  
	    	dataMap.put("cpu_usage",ProdUtils.Usage.cpu(jo));  
	    	dataMap.put("mem_usage",ProdUtils.Usage.mem(jo));  
	    	dataMap.put("disk_usage",ProdUtils.Usage.disk(jo));
	    	objects.add(dataMap);
		}
		
		model.addAttribute("op",op);
		model.addAttribute("collects",objects);
		
		return "original";
	}
	
	@GetMapping("ha")
	public String getHistoryAlarm(@RequestParam("op") String op,Model model) throws Exception {
		
		List<String> strs=bulidAlarmHistoryService.http_run_str(op);
		
		List<Map<String,String>> objects=Lists.newArrayList();
		
		for (String str : strs) {
			@SuppressWarnings("unchecked")
			Map<String,String> map=JSONObject.parseObject(str, Map.class);
			
			for (Map.Entry<String, String> entry : map.entrySet()) {
				if (entry.getKey().equals("alarmList")) {	
					JSONArray ja=JSONObject.parseArray(String.valueOf(entry.getValue()));
				    JSONObject json = null;
				    HashMap<String,String> dataMap = null;  
				    for (int i=0;i<ja.size();i++) {
				    	json=ja.getJSONObject(i);
				    	
				    	dataMap = new LinkedHashMap<String,String>();  
				    	dataMap.put("name",json.getString("name"));  
				    	dataMap.put("additional",json.getString("additional"));  
				    	dataMap.put("ip_addr",json.getString("ip_addr"));  
				    	dataMap.put("first_create_at",json.getString("first_create_at"));  
				    	dataMap.put("last_create_at",json.getString("last_create_at"));  
				    	dataMap.put("clear_time",json.getString("clear_time"));  
				    	dataMap.put("update_at",json.getString("update_at")); 
				    	
				    	objects.add(dataMap);					
					}
				}
			}
		}
		
//		排序告警
//		this.sortAlarm(objects);

		
		System.out.println(objects.size());
		
		model.addAttribute("op",op);
		model.addAttribute("collects",objects);
		
		return "original";
	}
	
	@GetMapping("ra")
	public String getRealAlarm(@RequestParam("op") String op,Model model) throws Exception {
		
		List<String> strs=bulidAlarmRealService.http_run(op);
		
		List<Map<String,String>> objects=Lists.newArrayList();
		
		for (String str : strs) {
			@SuppressWarnings("unchecked")
			Map<String,String> map=JSONObject.parseObject(str, Map.class);
			
			for (Map.Entry<String, String> entry : map.entrySet()) {
				if (entry.getKey().equals("alarmList")) {	
					JSONArray ja=JSONObject.parseArray(String.valueOf(entry.getValue()));
				    JSONObject json = null;
				    HashMap<String,String> dataMap = null;  
				    for (int i=0;i<ja.size();i++) {
				    	json=ja.getJSONObject(i);
				    	
				    	dataMap = new LinkedHashMap<String,String>();  
				    	dataMap.put("name",json.getString("name"));  
				    	dataMap.put("additional",json.getString("additional"));  
				    	dataMap.put("ip_addr",json.getString("ip_addr"));  
				    	dataMap.put("first_create_at",json.getString("first_create_at"));  
				    	dataMap.put("last_create_at",json.getString("last_create_at"));  
				    	dataMap.put("clear_time",json.getString("clear_time"));  
				    	dataMap.put("update_at",json.getString("update_at")); 
				    	
				    	objects.add(dataMap);					
					}
				}
			}
		}
		
		model.addAttribute("op",op);
		model.addAttribute("collects",objects);
		
		return "original";
	}
	
	
	
	private void sortAlarm(List<Map<String,String>> objects){
		Collections.sort(objects, new Comparator<Map<String,String>>() {
			@Override
			public int compare(Map<String,String> o1, Map<String,String> o2) {
				long ip1Result=ProdUtils.ipToLong(o1.get("ip_addr").toString());
				long ip2Result=ProdUtils.ipToLong(o2.get("ip_addr").toString());  
				
				if(ip1Result-ip2Result>0){  
		            return 1;  
		        }else if(ip1Result-ip2Result<0){  
		            return -1;  
		        }else{  
		            return 0;  
		        }  
			}
		});
	}
	
	/**
	 * 查找ip为某个值的Server对象
	 * @param serverList
	 * @param sip
	 */
	private Server findIpEuqalServer(List<Server> serverList,String sip){
		Object obj=CollectionUtils.find(serverList, new Predicate() {
			@Override
			public boolean evaluate(Object o) {
				if(sip.equals(ReflectUtils.getFieldValue("ipAddr", o)))
					return true;
				return false;
			}
		});
		
		return (Server)obj;
	}
}
